import 'dart:convert' as convert;

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
// import 'package:flutter_webview_pro/webview_flutter.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/generated/assets.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:flutter_syt/widgets/auto_image.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';

class WebHtmlPage extends StatefulWidget {
  final String html;
  final String? titile;
  final String? orderId;

  WebHtmlPage(this.html, {this.titile, this.orderId});
  @override
  State<StatefulWidget> createState() {
    return _WebHtmlPageState();
  }
}

class _WebHtmlPageState extends State<WebHtmlPage> {
  bool? isLoading = true;
  String? error;
  InAppWebViewController? _controller;
  var _title = '';
  // bool isLoadFrom = false;
  // bool _isFinished = false;
  @override
  void initState() {
    super.initState();
    if (widget.titile != null && (widget.titile ?? '').isNotEmpty) {
      _title = widget.titile ?? '';
    }
  }

  Future<bool> getprePayOrderInfo(orderId) async {
    var json = await API.shared.bridge.prePayOrderInfo(orderId);
    var status = json["pay_status"] as int;
    return status == 1;
  }

  Future<bool> checkPayStates() async {
    bool? preSuccess;

    if (widget.orderId != null) {
      // Assets
      EasyLoading.instance.loadingStyle = EasyLoadingStyle.light;
      EasyLoading.show(
        status: S().loading,
        maskType: EasyLoadingMaskType.black,
        indicator: const AutoImage(
          Assets.loading,
          width: 64,
          height: 64,
        )
      );
      try {
        preSuccess = await getprePayOrderInfo(widget.orderId);
        if (preSuccess == false) {
          await Future.delayed(Duration(seconds: 3));
          preSuccess = await getprePayOrderInfo(widget.orderId);
        }
      } catch (e) {}
      EasyLoading.dismiss();
    }
    Navigator.of(context).pop("$preSuccess");
    return true;
  }

  @override
  Widget build(BuildContext context) {
    var content = Stack(
      children: [
        InAppWebView(
          onWebViewCreated: (controller) {
            _controller = controller;
          },
          // initialUrl: buildUrl(),
          // javascriptMode: JavascriptMode.unrestricted,
          // onPageFinished: (result) {
          //   DLog('web加载完了');
          //   // ${widget.html}
          //   // _isFinished = true;
          //   error = null;
          //   if (isLoading == true) {
          //     Future.delayed(Duration(milliseconds: 100), () async {
          //       var t = await _controller?.getTitle();
          //       if (mounted) {
          //         setState(() {
          //           DLog('web加载完了 刷新State');
          //           if (_title.isEmpty) {
          //             _title = t ?? "";
          //           }

          //           isLoading = null;
          //         });
          //       }
          //     });
          //   }
          //   // if (isLoadFrom == false) {
          //   //   // isLoadFrom = true;
          //   //   // _controller?.loadUrl(Uri.dataFromString(widget.html,
          //   //   //         mimeType: 'text/html',
          //   //   //         encoding: convert.Encoding.getByName('utf-8'))
          //   //   //     .toString());
          //   // }
          // },
          // onWebResourceError: (webError) {
          //   setState(() {
          //     DLog('web加载完了 报错了: $webError');
          //     isLoading = null;
          //     error = webError.description;
          //   });
          // },
          // navigationDelegate: (NavigationRequest navigation) {
          //   DLog("即将打开 ${navigation.url}");
          //   if (navigation.url.contains('mall/orderDetail')) {
          //     // Navigator.pop(context);
          //     checkPayStates();
          //     return NavigationDecision.prevent;
          //   }
          //   return NavigationDecision.navigate;
          // },
        ),
        if (isLoading == true) Positioned.fill(child: loading()),
        if (error != null)
          Positioned.fill(
            child: Center(
              child: ViewStateErrorWidget(
                onPressed: ClickUtils.debounce(() {
                  isLoading = true;
                  _controller?.reload();
                }),
              ),
            ),
          ),
      ],
    );
    return WillPopScope(
        onWillPop: () async {
          return checkPayStates();
        },
        child: Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            // elevation: 1,
            title: Text(_title),
          ),
          body: content,
        ));
  }

  String buildUrl() {
    var content = '''
        <html>

        <head>
        </head>
${widget.html}
        <body>

        </body>
        </html>
    ''';
    return Uri.dataFromString(content,
            mimeType: 'text/html',
            encoding: convert.Encoding.getByName('utf-8'))
        .toString();
  }

  Widget loading() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            "assets/icons/empty.png",
            width: 80,
            height: 80,
          ),
          Container(
            height: 12,
          ),
          Text(
            S.of(context).loading,
            style:
                TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 14),
          ),
          Container(
            height: 20,
          ),
        ],
      ),
    );
  }
}
